package JsonConf;
# by Tao Lang: langtao123xxx@126.com
use strict;
use warnings;

use JSON qw/from_json to_json/;
use autodie qw/open close/;
use File::Copy;

use Mojo::Base 'Exporter';

our @EXPORT_OK = qw/get_conf json2href load_done update_done init_conf_file/;

# load json to hashref
sub json2href {
	my $fName = shift;
	my $href;

	my $fh;
	open $fh, '<', $fName;
	my $json_string = do { local $/; <$fh> };
	close $fh;

	$href = from_json($json_string);

	return $href;
}

# 获取配置信息
sub get_conf {

	# our $conf_file;
	my $conf_file = shift;
	return json2href($conf_file);
}

# load data from done.json
sub load_done {
	my ($jid,$data_dir) = @_; # $conf -- a hash ref
	my $done = {};
	my $done_fName = "$data_dir/$jid/done.json";
	if (-T $done_fName) {
		$done = json2href($done_fName);
	}

	return $done;
}

# 更新 done.json
sub update_done {

	# $done_info -- href
	# $conf -- href
	my ($done_info,$jid,$data_dir) = @_;

	my $done_fName = "$data_dir/$jid/done.json";

	my $fh;
	open $fh, '>', $done_fName;
	print $fh to_json($done_info, { pretty => 1 });
	close $fh;
}

# 初始的配置文件后缀为 .raw
sub init_conf_file {
	# 哪个服务
	my $f = shift;
	return 0 if (-e $f);

	my $raw = "$f.raw";
	die "$raw : not exists!" unless -e $raw;
	copy($raw, $f) or die "Copy failed: $!";

	return 0;
}

1;
